package com.demo.retrofit;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.demo.retrofit.Bean.User;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yihujiu.demo.R;

import java.util.HashMap;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitDemoActivity extends Activity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrofit);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.retrofix_post:
                PostDemo();
                break;
            case R.id.retrofix_postUser:
                PostUser();
                break;
            default:
                break;
        }
    }

    //采用基本的RequestBody,ResponseBody
    void PostDemo() {
        //日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("RetrofitLog", "retrofitBack = " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //HttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        String BASE_URL = "http://edi01.ysappstore.com:8052/"; //这里必须是BaseURL，只能到端口
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create()) //采用Gson转换
                .build();
        ExecuteServer service = retrofit.create(ExecuteServer.class);

        //Post参数
        Gson gson = new Gson();
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("APIKey", "173");
        paramsMap.put("CompanyID", "173");
        String strEntity = gson.toJson(paramsMap);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json;charset=UTF-8"), strEntity);

        //创建请求
        Call<ResponseBody> call = service.ExcuteByLabel(body);
        //请求并回掉
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    System.out.println(result);
                    toast(result);
                    result = response.body().string();// 不能两次调用,这里会报错
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    //retrofit采用JavaBean做请求参数
    void PostUser() {
        //日志拦截器
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(String message) {
                //打印retrofit日志
                Log.i("RetrofitLog", "retrofitBack = " + message);
            }
        });
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //HttpClient
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .build();

        Gson gson = new GsonBuilder()
                //配置你的Gson
                .setDateFormat("yyyy/MM/dd hh:mm:ss")
                .create();

        String BASE_URL = "http://edi01.ysappstore.com:8052/"; //这里必须是BaseURL，只能到端口
        //String BASE_URL = "http://192.168.8.187/";
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(client)
                //.addConverterFactory(GsonConverterFactory.create()) //默认gson
                .addConverterFactory(GsonConverterFactory.create(gson)) //配置的gson
                .build();

        //Post参数
        User user = new User();
        //Web服务
        UserServer service = retrofit.create(UserServer.class);
        //创建请求
        Call<ResponseBody> call = service.UserLogin(user);
        //请求并回掉
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String result = response.body().string();
                    System.out.println(result);
                    toast(result);
                } catch (Exception e) {
                    System.out.println(e);
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
                toast(t.getMessage());
            }
        });
    }

    void toast(String msg) {
        Toast.makeText(RetrofitDemoActivity.this, msg, Toast.LENGTH_LONG).show();
    }


}
